package com.example.demo.controller

import com.auth0.jwt.JWT
import com.auth0.jwt.algorithms.Algorithm
import com.example.demo.auth.AdminUserInfo
import com.example.demo.auth.Auth
import com.example.demo.auth.AuthHelper
import com.example.demo.auth.BaseUserInfo
import com.example.demo.service.sso.EasyRbacService
import com.example.demo.service.sso.UserResource
import com.example.demo.utils.toOneResources
import com.example.demo.utils.toTree
import org.springframework.beans.factory.annotation.Value
import org.springframework.web.bind.annotation.*

import javax.servlet.http.HttpServletRequest
import java.time.LocalDateTime
import java.time.ZoneId
import java.util.Date

@RestController
@RequestMapping("/sso")
class AdminSsoController(private val easyRbacService: EasyRbacService) {

    @Value("\${jwt.easy-rbac-key}")
    private val jwtToken: String? = null

    @PostMapping
    fun getAuthInfo(@RequestParam token: String): String {
        val easyRbacUserInfo = this.easyRbacService.getEasyRbacUserInfo(token)
        val algorithm = Algorithm.HMAC256(this.jwtToken!!)
        val expireOn = LocalDateTime.now().plusHours(12)
        val expireDate = Date.from(expireOn.atZone(ZoneId.systemDefault()).toInstant())
        val result = JWT.create()
                .withIssuer("ER")
                .withClaim("userId", easyRbacUserInfo.id)
                .withClaim("token", token)
                .withClaim("name", easyRbacUserInfo.realName)
                .withExpiresAt(expireDate)
                .sign(algorithm)
        return String.format("ER %s", result)
    }

    @Auth(resourceCode = "getMenu")
    @GetMapping("user_menu")
    fun getUserResource(userInfo:BaseUserInfo): List<UserResource> {
        val adminUser = userInfo as AdminUserInfo
        val userResource = this.easyRbacService.getUserResource(adminUser.token)
        val arrayList = ArrayList<UserResource>()
        userResource.toOneResources(arrayList)
        arrayList.toTree()
        return userResource
    }
}